We've covered:
but we haven't shown whether a program is getting the right answer and whether it is still getting the right answers as we change the program
We need to:
make sure we know what 'correct' actually means
as with real carpentry - time is saved by carefully measuring before cutting wood
for example
In [2]:
numbers = [1.5, 2.3, 0.7, -0.001, 4.4]
total = 0.0
for n in numbers:
assert n > 0.0, 'Data should only contain positve values'
total += n
print('total is: ', total)
In [4]:
def normalize_rectangle(rect):
'''Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis.'''
assert len(rect) == 4, 'Rectangles must contain 4 coordinates'
x0, y0, x1, y1 = rect
assert x0 < x1, 'Invalid X coordinates'
assert y0 < y1, 'Invalid Y coordinates'
dx = x1 - x0
dy = y1 - y0
if dx > dy:
scaled = float(dx) / dy
upper_x, upper_y = 1.0, scaled
else:
scaled = float(dx) / dy
upper_x, upper_y = scaled, 1.0
assert 0 < upper_x <= 1.0, 'Calculated upper X coordinate invalid'
assert 0 < upper_y <= 1.0, 'Calculated upper Y coordinate invalid'
return (0, 0, upper_x, upper_y)
In [5]:
print(normalize_rectangle((0.0, 1.0, 2.0))) #missing the fourth coordinate
In [7]:
print(normalize_rectangle((0.0,0.0, 1.0, 5.0)))
In [8]:
print(normalize_rectangle((0.0,0.0,5.0,1.0)))
range_overlap
function that should pass tests, if range_overlap
fails, fix it and re-run test functionhere are three test functions for range_overlap:
In [9]:
assert range_overlap([ (0.0, 1.0) ]) == (0.0, 1.0)
assert range_overlap([ (2.0, 3.0), (2.0, 4.0) ]) == (2.0, 3.0)
assert range_overlap([ (0.0, 1.0), (0.0, 2.0), (-1.0, 1.0) ]) == (0.0, 1.0)
In [10]:
assert range_overlap([ (0.0, 1.0), (5.0, 6.0) ]) == ???
In [ ]: